package org.pizza.dlock.distributed.lock;

import org.pizza.dlock.distributed.lock.api.DistributedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @author 高巍
 * @date 2018年08月31日 16:45
 */
public class RedissonLock implements DistributedLock {

    public RedissonLock(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    private RedissonClient redissonClient;

    private RLock getLock(String key) {
        return redissonClient.getLock(key);
    }

    public void lock(String key) {
        getLock(key).lock();
    }

    public void lock(String key, Integer seconds) {
        getLock(key).lock(seconds, TimeUnit.SECONDS);
    }

    @Override
    public void unlock(String key) {
        getLock(key).unlock();
    }


    @Override
    public boolean tryLock(String key) {
        return getLock(key).tryLock();
    }


    @Override
    public boolean tryLock(String key, Long waitTime) {
        try {
            return getLock(key).tryLock(waitTime, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }


    @Override
    public boolean tryLock(String key, Long waitTime, Long leaseTime) {
        try {
            return getLock(key).tryLock(waitTime, leaseTime, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean isLocked(String key) {
        return getLock(key).isLocked();
    }

    public RedissonClient getRedissonClient() {
        return redissonClient;
    }

    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }
}
